class MyBlockingQueue {
    private String[] temp = null;
    private int head = 0;
    private int cur = 0;
    private int size = 0;//定义size记录队列中的元素个数
    private Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        temp = new String[capacity];
    }

    public void put(String x) throws InterruptedException {
        synchronized(locker){
            while (size >= temp.length) { //改用while多做一步确认操作
                // 队列满 (后续需要让这个代码阻塞)
                //return;
                locker.wait();//队列满 (阻塞)
            }
            temp[cur] = x;
            cur++;
            if (cur >= temp.length) {
                cur = 0;//手动将cur位置放至队首
            }
            size++;
            locker.notify();//入队列后唤醒
        }
    }

    public String take() throws InterruptedException {
        String ret = null;
        synchronized (locker) {
            while (size == 0) { //改用while多做一步确认操作
                //队列空 (后续同样需要让其阻塞)
                //return null;
                locker.wait();//队列空 出队列时阻塞
            }
            ret = temp[head];
            head++;
            if (head >= temp.length) {
                head = 0;//走回起点
            }
            size--;
            locker.notify();//队列不满时唤醒
        }
        return ret;
    }
}
public class Custom_BlockingQueue {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(100);
//        myBlockingQueue.put("jcw");
//        myBlockingQueue.put("lzx");
//        myBlockingQueue.put("ld");
//        myBlockingQueue.put("lcm");
//        System.out.println(myBlockingQueue.take());
//        System.out.println(myBlockingQueue.take());
//        System.out.println(myBlockingQueue.take());
//        System.out.println(myBlockingQueue.take());

        //简易实现生产者-消费者模型
        Thread t1 = new Thread(()->{
            int n = 1;
            while(true){
                try {
                    myBlockingQueue.put(n+" ");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产元素："+n);
                n++;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(()->{
            while(true){
                String s = null;
                try {
                   s = myBlockingQueue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费元素："+s);
            }
        });
        t1.start();
        t2.start();
    }
}
